package com.ifdom.thread.poolpractice;

import com.jdbc.JDBCUtils;
import org.junit.jupiter.api.function.Executable;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.*;

/**
 * CountDownLatch使用
 *
 * 优化：使用 CompletableFuture
 * @Author ifredomvip@gmail.com
 * @Date 2022/10/10 15:41
 * @Version 1.0.0
 * @Description
 **/
public class MultThreadUpdate {
    static private final Integer threadCount = 3;

    static CountDownLatch countDownLatch = new CountDownLatch(threadCount);

    public static void main(String[] args) {

        ExecutorService executorService = new ThreadPoolExecutor(3,
                8,
                300,
                TimeUnit.SECONDS,
                new SynchronousQueue<>(),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );


        for (int i = 0; i < 3; i++) {
            Runnable task = () -> {
                try {
                    System.out.println("子线程" + Thread.currentThread().getName() + "开始执行");
                    Thread.sleep((long) (Math.random() * 3000));
                    System.out.println("子线程" + Thread.currentThread().getName() + "执行完成");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    countDownLatch.countDown();//当前线程调用此方法，则计数减一
                }
            };
            executorService.execute(task);
        }


        try {
            System.out.println("主线程" + Thread.currentThread().getName() + "等待子线程执行完成...");
            countDownLatch.await();//阻塞当前线程，直到计数器的值为0
            System.out.println("主线程" + Thread.currentThread().getName() + "开始执行...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
